package kroketwebspring.dao;

import java.util.HashMap;
import javax.servlet.http.HttpSession;

import kroketwebspring.domain.Product;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class OrderDAOImpl extends JdbcDaoSupport implements OrderDAO {

	@SuppressWarnings("unchecked")
	@Override
	public void insertOrderIntoDB(HttpSession session, String name,
			String address, String town, String phone) {
		// get the products
		HashMap<Integer, Product> products = (HashMap<Integer, Product>) session.getAttribute("products");
		
		// insert query
		String insertQuery = "INSERT INTO orders (order_name, order_address, order_town, order_phone)"
			+ " VALUES ('" + name + "', '" + address + "', '" + town + "', '" + phone + "');";
		
		int orderId = this.getJdbcTemplate().update(insertQuery);
		
		if (products.size() > 0) {
			for (Product p : products.values()) {
				insertOrderProductIntoDB(orderId, p.getId(), p.getAmount());
				updateProductStock(p.getId(), p.getAmount());
			}
		}
	}

	@Override
	public void insertOrderProductIntoDB(int orderId, int productId, int amount) {
		// insert query
		String query = "INSERT INTO order_product (order_id, product_id, order_product_amount)"
			+ " VALUES ('" + orderId + "', '" + productId + "', '" + amount + "');";
		
		this.getJdbcTemplate().execute(query);
	}

	@Override
	public void updateProductStock(int productId, int amount) {
		String stockQuery = "SELECT product_stock"
			+ " FROM product"
			+ " WHERE product_id = '" + productId + "';";
		
		int oldStock = this.getJdbcTemplate().queryForInt(stockQuery);
		int newStock = oldStock - amount;
		
		String updateQuery = "UPDATE product"
			+ " SET product_stock = '" + newStock + "';";
		
		this.getJdbcTemplate().update(updateQuery);
	}

}
